package ssoUser

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"chainmaker.org/chainmaker/smarteditor/conf"
	"chainmaker.org/chainmaker/smarteditor/logger"
	uuid "github.com/satori/go.uuid"
)

var log = logger.Get()

type SsoUser struct {
	UUID           uuid.UUID `json:"uuid" gorm:"column:uuid;index;comment:用户UUID"`
	UserName       string    `gorm:"column:user_name;comment:用户名" json:"userName"`
	UserId         int64     `json:"userId" gorm:"column:user_id;comment:用户ID"`
	PhoneNumber    string    `gorm:"column:phone_number;comment:电话号" json:"phoneNumber"`
	IdCard         string    `gorm:"column:id_card;comment:身份证" json:"idCard"`
	Name           string    `gorm:"column:name;comment:姓名" json:"name"`
	State          int8      `gorm:"column:state;comment:状态" json:"state"`
	EnterpriseName string    `gorm:"varchar(255);column:enterprise_name;comment:公司名" json:"enterpriseName"`
	AuthGrade      int8      `gorm:"column:auth_grade;comment:认证等级" json:"authGrade"`
	AuthResult     string    `gorm:"column:auth_result;comment:认证结果" json:"authResult"`
	HeadImg        string    `gorm:"column:head_img;comment:头像" json:"headImg"`
	CreatedAtTime  time.Time `gorm:"column:created_at;comment:创建时间" json:"createdAtTime"`
	LoginAtTime    time.Time `gorm:"column:login_at;default:null;comment:登录时间" json:"loginAtTime"`
	AuthAtTime     time.Time `gorm:"column:auth_at;default:null;comment:认证时间" json:"authAtTime"`
	Address        string    `gorm:"varchar(1024);column:address;comment:地址" json:"address"`
}

type UsersRes struct {
	Code int        `json:"code"`
	Msg  string     `json:"msg"`
	Data *UsersData `json:"data"`
}

type UsersData struct {
	Total    int64      `json:"total"`
	Page     int64      `json:"page"`
	PageSize int64      `json:"pageSize"`
	List     []*SsoUser `json:"list"`
}

func GetUserInfoByUserId(userId string) (*SsoUser, error) {
	urlString := fmt.Sprintf("http://%s/opennetSso/manager/users", conf.Wide.SsoOAuthServer)
	method := "POST"

	payload := strings.NewReader(fmt.Sprintf("{"+
		"\"sortKey\": \"auth_at\","+
		"\"userId\": \"%s\","+
		"\"type\": 1,"+
		"\"page\": 1"+
		"}", userId))

	client := &http.Client{
		//Transport: &http.Transport{
		//	TLSClientConfig: &tls.Config{
		//		InsecureSkipVerify: true,
		//	},
		//},
	}
	req, err := http.NewRequest(method, urlString, payload)

	if err != nil {
		log.Error(err.Error())
		return nil, err
	}
	req.Header.Add("x-token", conf.Wide.SsoToken)
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	log.Infof(string(body))
	var response UsersRes
	err = json.Unmarshal(body, &response)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	if response.Data == nil || len(response.Data.List) == 0 {
		return nil, errors.New("no user by userId")
	}
	return response.Data.List[0], nil
}
